import React from 'react';
import { Button, Col, Form, Row } from 'antd';
import { AxCreateForm, AxCreateGridThreeFormPage } from '@/components/AxForm/AxCreateForm';
import { useState, useEffect } from 'react';
import { AxInput, AxLabel, AxSearch, AxSelect, AxTextArea } from '@/components/AxForm/AxFormItem';
import { AxTabs, AxTabPane, AxCard, AxButtonOk, AxCardGridThree } from '@/components/AxBase';
import { axhelper } from '@/shared/axhelper';
import Chart from './lib/chart';
import { axhttp } from '@/shared/axhttp';
import { AxSuccess } from '@/components/AxBase';
import Record from './lib/record';
import User from './lib/user';
import { axconst } from '@/shared/axconst';
import { axurl } from '@/shared/axurl';
import { AxModalShowPicture } from '@/components/AxForm/AxFormItem/AxUpload';
import IconFont from '@/assets/iconfont';
// import { Enrolled, Fee, Extend, Trail, Enroll, Base } from '@/pages/enroll/common/components/detail';
import { AxButton, AxDescriptions, AxItem } from '@/components/AxBase';
import { router } from 'umi';

const { getX, postFormX } = axhttp;
/**
 * 
 * @param FlowComponent 流程类型对应的组件
 * @param url 请求地址 
 * @param operateType  false - 查看，true - 处理
 */
const DealFlow: React.FC<any> = props => {
    const {
        form,
        FlowComponent,
        flowProps = {},
        extraParams = {},
        title,
        url,
        recordId,
        operateType = false,
        tabs = [],
    } = props;
    const [result, setResult] = useState<any>({});
    const [successVisible, setSuccessVisible] = useState(false);
    /** 用户对于该流程的操作权限 */
    const [userDealType, setUserDealType] = useState<any>([]);
    /** 是否可以修改表单数据 */
    const [canEdit, setCanEdit] = useState<any>(false);
    /** 附件信息 */
    const [attachments, setAttachments] = useState<any>([]);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewSrc, setPreviewSrc] = useState(false);
    const [agreeVisible, setAgreeVisible] = useState(false);
    const [backVisible, setBackVisible] = useState(false);
    const [forwardAndAppointVisible, setForwardAndAppointVisible] = useState(false);
    const [nodeVisible, setNodeVisible] = useState(false);
    const [rejectVisible, setRejectVisible] = useState(false);
    const [forwardAndAppointType, setForwardAndAppointType] = useState('');
    /** 下一节点处理人员列表 */
    const [nextNode, setNextNode] = useState<any>([]);
    /** 下一节点处理人员列表原始数据 */
    const [nextNodeOriginal, setNextNodeOriginal] = useState<any>([]);
    const [values, setValues] = useState<any>({});

    useEffect(() => {
        if (recordId) {
            /** 查询某条流程的信息 */
            getX(url.readOne, { recordId: recordId }).then((res: any) => {
                setValues(res.data && res.data || {});
            });
            /** 获取用户对于该流程的操作权限 */
            getX(url.readUserDealType, { recordId: recordId }).then((res: any) => {
                setUserDealType(res.data && res.data.dealType || []);
                setCanEdit(res.data && res.data.edit);
            });
            /** 获取附件列表 */
            getX(axurl.enroll.common.readAttachmentList, { dataId: recordId }).then((res: any) => {
                setAttachments(res.data);
            });
        }
    }, [recordId]);

    /** 成功信息 */
    const Content = ({ result }: any) => (
        <AxDescriptions title={title}>
            <AxItem label="姓名" span={1}>{result.name}</AxItem>
            <AxItem label="身份证" span={1}>{result.idcard}</AxItem>
            <AxItem label="流程编号" span={1}>{result.id}</AxItem>
            <AxItem label="标题" span={3}>{result.title}</AxItem>
            <AxItem label="内容" span={3}>{result.description}</AxItem>
            {result.userName && <AxItem label="接收人" span={3}>{result.userName}</AxItem>}
            {result.remark && <AxItem label="备注" span={3}>{result.remark}</AxItem>}
        </AxDescriptions>
    );

    /** 成功页面额外的操作信息 */
    const Extra = () => (
        <>
            <AxButton className="ax-no-class ax-btn-color3" icon="unordered-list" onClick={() => router.push('/center/s/flow/need')} >流程列表</AxButton>
        </>
    );

    /** 展示附件 */
    const handleShowAttachments = (e: any, src: any) => {
        /** 是图片地址 */
        if (axconst.valid.picture.reg.test(src)) {
            e && e.preventDefault();
            setPreviewSrc(src);
            setPreviewVisible(true);
        }
    };

    /** 附件展示弹框属性 */
    const previewProps = {
        visible: previewVisible,
        handleCancel: () => setPreviewVisible(false),
        src: previewSrc,
    };

    /** 改变接收人 */
    const handleChangeNode = (value: any) => {
        const f = nextNodeOriginal.find((f: any) => f.value === value);
        if (f) {
            form.setFieldsValue({
                nextUserId: f.userId,
                nextNodeId: f.nodeId,
                userName: f.userName,
            });
        }
    }


    /** 批准弹框 */
    const handleAgreeModal = () => {
        /** 获取下一节点处理人员列表 */
        return getX(url.readNextNode, { recordId: recordId }).then((res: any) => {
            // /** 没有接收人，直接提交数据 */
            // if (res.data.length === 0) {
            //     handleCreateAgree(form.getFieldsValue());
            // }
            // /** 只有一个接收人，默认后，直接提交数据 */
            // else if (res.data.length === 1) {
            //     const d = res.data[0];
            //     handleCreateAgree({
            //         ...form.getFieldsValue(),
            //         nextUserId: d.userId,
            //         nextNodeId: d.nodeId,
            //     });
            // }
            // /** 多个接收人，让用户选择 */
            // else {
            const d = res.data.map((m: any) => ({
                ...m,
                text: m.userName,
                value: axhelper.guid(),
            }));
            setNextNode(d);
            setNextNodeOriginal(d);
            setAgreeVisible(true);
            // }
        });
    }
    /** 批准 */
    const handleCreateAgree = (fields: any) => {
        return postFormX(url.agree, null, {
            ...fields,
            ...extraParams,
        }).then(() => {
            setResult({
                ...values,
                ...fields,
                ...extraParams,
            });
            setSuccessVisible(true);
        });
    }
    /** 批准弹框属性 */
    const agreeProps = {
        form: form,
        visible: agreeVisible,
        nextNode: nextNode,
        handleCreate: handleCreateAgree,
        handleChangeNode: handleChangeNode,
        handleVisible: () => setAgreeVisible(false),
    };


    /** 回退弹框 */
    const handleBackModal = () => {
        /** 获取驳回接受人列表 */
        return getX(url.readBackUserList, { recordId: recordId }).then((res: any) => {
            /** 没有接收人，直接提交数据 */
            // if (res.data.length === 0) {
            //     handleCreateBack(form.getFieldsValue());
            // }
            // /** 只有一个接收人，默认后，直接提交数据 */
            // else if (res.data.length === 1) {
            //     const d = res.data[0];
            //     handleCreateBack({
            //         ...form.getFieldsValue(),
            //         nextUserId: d.userId,
            //         nextNodeId: d.nodeId,
            //     });
            // }
            // /** 多个接收人，让用户选择 */
            // else {
            const d = res.data.map((m: any) => ({
                ...m,
                text: `${m.userName} - ${m.nodeName}`,
                value: axhelper.guid(),
            }));
            setNextNode(d);
            setNextNodeOriginal(d);
            setBackVisible(true);
            // }
        });
    }
    /** 回退 */
    const handleCreateBack = (fields: any) => {
        return postFormX(url.back, null, {
            ...fields,
            ...extraParams,
        }).then(() => {
            setResult({
                ...values,
                ...fields,
                ...extraParams,
            });
            setSuccessVisible(true);
        });
    }
    /** 回退弹框属性 */
    const backProps = {
        form: form,
        visible: backVisible,
        nextNode: nextNode,
        handleCreate: handleCreateBack,
        handleChangeNode: handleChangeNode,
        handleVisible: () => setBackVisible(false),
    };


    /** 转发、指派弹框 */
    const handleForwardAndAppointModal = (type: any) => {
        setForwardAndAppointType(type);
        setForwardAndAppointVisible(true);
        return Promise.resolve();
    }
    /** 转发、指派 */
    const handleCreateForwardAndAppoint = (fields: any) => {
        const u = forwardAndAppointType === 'forward' ? url.forward : url.appoint;
        return postFormX(u, null, {
            ...fields,
            ...extraParams,
        }).then(() => {
            setResult({
                ...values,
                ...fields,
                ...extraParams,
            });
            setSuccessVisible(true);
        });
    }
    /** 转发、指派弹框属性 */
    const forwardAndAppointProps = {
        form: form,
        visible: forwardAndAppointVisible,
        handleCreate: handleCreateForwardAndAppoint,
        type: forwardAndAppointType,
        handleVisible: () => setForwardAndAppointVisible(false),
    };


    /** 批注 */
    const handleCreateNode = (fields: any) => {
        return postFormX(url.note, null, {
            ...fields,
            ...extraParams,
        }).then(() => {
            setResult({
                ...values,
                ...fields,
                ...extraParams,
            });
            setSuccessVisible(true);
        });
    }
    /** 批注弹框 */
    const handleNodeModal = () => {
        setNodeVisible(true);
        return Promise.resolve();
    }
    /** 批准弹框属性 */
    const nodeProps = {
        form: form,
        visible: nodeVisible,
        handleCreate: handleCreateNode,
        handleVisible: () => setNodeVisible(false),
    };


    /** 驳回 */
    const handleRejectNode = (fields: any) => {
        return postFormX(url.reject, null, {
            ...fields,
            ...extraParams,
        }).then(() => {
            setResult({
                ...values,
                ...fields,
                ...extraParams,
            });
            setSuccessVisible(true);
        });
    }
    /** 驳回弹框 */
    const handleRejectModal = () => {
        setRejectVisible(true);
        return Promise.resolve();
    }
    /** 驳回弹框属性 */
    const rejectProps = {
        form: form,
        visible: rejectVisible,
        handleCreate: handleRejectNode,
        handleVisible: () => setRejectVisible(false),
    };


    return (
        <>
            {!successVisible && (
                <AxCreateGridThreeFormPage
                    form={form}
                    title={title}
                    cardPageOperateBtn={false}
                    items={[
                        <AxTabs defaultActiveKey="tab0" wholerow='three'
                            tabBarExtraContent={
                                <>
                                    <Button type='link' onClick={() => {
                                        router.goBack()
                                    }} >
                                        <IconFont style={{ position: 'absolute', top: 17, right: 24 }} type='iconfanhui' />
                                    </Button>
                                </>
                            }
                        >
                            <AxTabPane tab="表单信息" key="tab0">
                                <Row>
                                    <Col span={16}>
                                        <AxCardGridThree>
                                            <AxLabel
                                                form={form}
                                                label="姓名"
                                                field="name"
                                                // wholerow='three'
                                                value={values.name}
                                            />
                                        </AxCardGridThree>
                                        <AxCardGridThree>
                                            <AxLabel
                                                form={form}
                                                label="身份证"
                                                field="idcard"
                                                // wholerow='three'
                                                value={values.idcard}
                                            />
                                        </AxCardGridThree>
                                        <AxCardGridThree>
                                            <AxLabel
                                                form={form}
                                                label="流程编号"
                                                field="title"
                                                // wholerow='three'
                                                value={values.id}
                                            />
                                        </AxCardGridThree>
                                        <AxLabel
                                            form={form}
                                            label="标题"
                                            field="title"
                                            wholerow='three'
                                            value={values.title}
                                        />
                                        <AxLabel
                                            form={form}
                                            label="内容"
                                            field="description"
                                            wholerow='three'
                                            value={values.description}
                                        />
                                        <AxCardGridThree span={3}>
                                            <AxLabel
                                                label="附件信息"
                                                wholerow='three'
                                            >
                                                {attachments && attachments.map((i: any, idx: any) => (
                                                    <a
                                                        key={idx}
                                                        href={i.src}
                                                        onClick={e => handleShowAttachments(e, i.src)}
                                                    >
                                                        {i.name}&emsp;
                                                    </a>
                                                ))}
                                            </AxLabel>
                                        </AxCardGridThree>
                                    </Col>
                                    <Col span={16}>
                                        <FlowComponent recordId={recordId} canEdit={canEdit && operateType} {...flowProps} />
                                    </Col>
                                    {operateType && <Col span={16}>
                                        <AxCard flex={24} height={55} bodyStyle={{ padding: 10, paddingRight: 0, float: 'right' }}>
                                            <div className='ant-modal-footer' style={{ paddingRight: 0, borderTop: '0' }}>
                                                <>
                                                    {/*  提交 1
                                                 批准 2 
                                                 驳回 3 
                                                 回退 4
                                                 转发 5 
                                                 指派 6 
                                                 批注 7 
                                                 完结 8 
                                                 归档 9  */}
                                                    {userDealType.find((f: any) => f === 2) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={handleAgreeModal} flag='continue'>
                                                            <IconFont type='iconpizhun' />批准
                                            </AxButtonOk>}
                                                    {userDealType.find((f: any) => f === 3) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={handleRejectModal} flag='continue'>
                                                            <IconFont type='iconbohui' />驳回
                                            </AxButtonOk>}
                                                    {userDealType.find((f: any) => f === 4) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={handleBackModal} flag='continue'>
                                                            <IconFont type='iconhuitui' />回退
                                            </AxButtonOk>}
                                                    {userDealType.find((f: any) => f === 5) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={() => handleForwardAndAppointModal('forward')} flag='continue'>
                                                            <IconFont type='iconzhuanfa' />转发
                                            </AxButtonOk>}
                                                    {userDealType.find((f: any) => f === 6) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={() => handleForwardAndAppointModal('appoint')} flag='continue'>
                                                            <IconFont type='iconzhipai' />指派
                                            </AxButtonOk>}
                                                    {userDealType.find((f: any) => f === 7) > -1
                                                        && <AxButtonOk icon={undefined} form={form} handleClick={handleNodeModal} flag='continue'>
                                                            <IconFont type='iconpizhu' />批注
                                            </AxButtonOk>}
                                                </>
                                            </div>
                                        </AxCard>
                                    </Col>}
                                    <Col span={16}>
                                        <Record url={url} recordId={recordId} />
                                    </Col>
                                </Row>
                            </AxTabPane>
                            {/* <AxTabPane tab="学生信息" key="tab1" >
                                <AxTabs defaultActiveKey="tab0" wholerow='three'>
                                    <AxTabPane tab="基础信息" key="tab2" >
                                        <Base customerId={values.customerId} />
                                    </AxTabPane>
                                    <AxTabPane tab="报考信息" key="tab3">
                                        <Enroll enrollId={values.enrollId} />
                                    </AxTabPane>
                                    <AxTabPane tab="在校信息" key="tab4">
                                        <Enrolled studentStatusId={values.studentId} />
                                    </AxTabPane>
                                    <AxTabPane tab="缴费信息" key="tab5">
                                        <Fee customerId={values.customerId} studentStatusId={values.studentId} />
                                    </AxTabPane>
                                    <AxTabPane tab="扩展信息" key="tab6">
                                        <Extend customerId={values.customerId} />
                                    </AxTabPane>
                                    <AxTabPane tab="轨迹信息" key="tab7">
                                        <Trail customerId={values.customerId} />
                                    </AxTabPane>
                                </AxTabs>
                            </AxTabPane> */}
                            <AxTabPane tab="流程图" key="tab2">
                                <Chart recordId={recordId} url={url.readFlowChart} />
                            </AxTabPane>
                        </AxTabs>
                    ]}
                    hiddenItems={[
                        <AxInput form={form} field="userName" htmlHidden={true} />,
                        <AxInput form={form} field="nextUserId" htmlHidden={true} />,
                        <AxInput form={form} field="nextNodeId" htmlHidden={true} />,
                        <AxInput form={form} field="recordId" htmlHidden={true} value={recordId} />,
                    ]}
                />
            )}
            {
                successVisible && (
                    <AxSuccess subTitle={`本次${title}信息如下，请确认！`}
                        content={Content && <Content result={result} />}
                        extra={Extra && <Extra />}
                    />
                )
            }
            {previewVisible && <AxModalShowPicture {...previewProps} />}
            {agreeVisible && <AxModalAgree {...agreeProps} />}
            {backVisible && <AxModalBack {...backProps} />}
            {forwardAndAppointVisible && <AxModalForwardAndAppoint {...forwardAndAppointProps} />}
            {nodeVisible && <AxModalNode {...nodeProps} />}
            {rejectVisible && <AxModalReject {...rejectProps} />}
        </>
    );
};

/**
 * 批准
 */
export function AxModalAgree(props: any) {
    const { form, nextNode, handleChangeNode, handleCreate: handleCreateFromProps, handleVisible } = props;

    const handleCreate = (fields: any) => {
        if (handleCreateFromProps) {
            return handleCreateFromProps(fields).then(() => {
                handleVisible(false);
                return Promise.reject();
            });
        }
        else {
            return Promise.reject();
        }
    }

    return (
        <AxCreateForm
            {...props}
            title='批准'
            handleCreate={handleCreate}
            items={[
                <AxTextArea form={form} label="签字意见" field="remark" required />,
                nextNode && nextNode.length > 0 && <AxSelect form={form} label="接收人" field="guid" data={nextNode} onChange={handleChangeNode} autoSelect required />,
            ]}
        />
    );
}

/**
 * 回退
 */
export function AxModalBack(props: any) {
    const { form, nextNode, handleChangeNode, handleCreate: handleCreateFromProps, handleVisible } = props;

    const handleCreate = (fields: any) => {
        if (handleCreateFromProps) {
            return handleCreateFromProps(fields).then(() => {
                handleVisible(false);
                return Promise.reject();
            });
        }
        else {
            return Promise.reject();
        }
    }

    return (
        <AxCreateForm
            {...props}
            title='回退'
            handleCreate={handleCreate}
            items={[
                <AxTextArea form={form} label="签字意见" field="remark" required />,
                <AxSelect form={form} label="接收人" field="guid" data={nextNode} onChange={handleChangeNode} autoSelect required />
            ]}
        />
    );
}

/**
 * 转发和指派
 */
export function AxModalForwardAndAppoint(props: any) {
    const { form, handleCreate: handleCreateFromProps, type, handleVisible } = props;
    const [userVisible, setUserVisible] = useState(false);
    const [searchLoading, setSearchLoading] = useState(false);
    const [keyword, setKeyword] = useState('');
    const title = type === 'forward' && '转发' || '指派';

    const handleCreate = (fields: any) => {
        if (handleCreateFromProps) {
            return handleCreateFromProps(fields).then(() => {
                handleVisible(false);
                return Promise.reject();
            });
        }
        else {
            return Promise.reject();
        }
    }

    /** 展示接收人 */
    const handleSearch = (v: any, e: any) => {
        setKeyword(v);

        /** 清空选项 */
        if (v === '' && e.currentTarget.defaultValue) return;
        setUserVisible(true);
    };

    /** 接收人选中回调 */
    const handleSelect = (_: any) => {
        if (_ && _.value) {
            form.setFieldsValue({
                nextUserId: _.value,
                nextUserName: _.text,
            });
        }
    };

    return (
        <>
            <AxCreateForm
                {...props}
                title={title}
                handleCreate={handleCreate}
                items={[
                    <AxTextArea form={form} label="签字意见" field="remark" required />,
                    <AxSearch
                        form={form}
                        label="接收人"
                        placeholder="请输入姓名/手机号"
                        field="nextUserName"
                        loading={searchLoading}
                        onSearch={handleSearch}
                        allowClear={true}
                        enterButton
                        required
                    />,
                ]}
                hiddenItems={[
                    <AxInput form={form} field="nextUserId" htmlHidden={true} />,
                ]}
            />
            {userVisible && (
                <User
                    autoSelect
                    searchValue={keyword}
                    handleVisible={setUserVisible}
                    handleSelect={handleSelect}
                    setSearchLoading={setSearchLoading}
                />
            )}
        </>
    );
}

/**
 * 批注
 */
export function AxModalNode(props: any) {
    const { form, handleCreate: handleCreateFromProps, handleVisible } = props;

    const handleCreate = (fields: any) => {
        if (handleCreateFromProps) {
            return handleCreateFromProps(fields).then(() => {
                handleVisible(false);
                return Promise.reject();
            });
        }
        else {
            return Promise.reject();
        }
    }

    return (
        <AxCreateForm
            {...props}
            title='批注'
            handleCreate={handleCreate}
            items={[
                <AxTextArea form={form} label="签字意见" field="remark" required />,
            ]}
        />
    );
}

/**
 * 驳回
 */
export function AxModalReject(props: any) {
    const { form, handleCreate: handleCreateFromProps, handleVisible } = props;

    const handleCreate = (fields: any) => {
        if (handleCreateFromProps) {
            return handleCreateFromProps(fields).then(() => {
                handleVisible(false);
                return Promise.reject();
            });
        }
        else {
            return Promise.reject();
        }
    }

    return (
        <AxCreateForm
            {...props}
            title='驳回'
            handleCreate={handleCreate}
            items={[
                <AxTextArea form={form} label="签字意见" field="remark" required />,
            ]}
        />
    );
}

export default Form.create<any>()(DealFlow);
